package com.harassment.interception.interception.sms;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.telephony.SmsMessage;
import android.util.Log;

import com.harassment.interception.data.databases.HIDBUtil;
import com.harassment.interception.data.databases.HIDatabase;
import com.harassment.interception.data.databases.entities.BlackList;
import com.harassment.interception.data.databases.entities.InterceptedSms;
import com.harassment.interception.data.databases.entities.WhiteList;
import com.harassment.interception.ui.fragments.interceptRecord.smsFragment.SmsListAdapter;
import com.harassment.interception.ui.fragments.setting.SettingFragment;

import java.util.Date;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class SmsInterception {
    private static SmsListAdapter sSmsListAdapter;
    private static LinearLayoutManager sLinearLayoutManager;
    private static final String TAG = "SmsInterception";

    public static InterceptedSms[] getInterceptedSms(Intent intent) {
        InterceptedSms[] interceptedSms = null;
        //Intent -> Bundle
        Log.d(TAG, "smsIntercept: Intent -> Bundle");
        Bundle bundle = intent.getExtras();
        //Bundle -> Object[]
        Log.d(TAG, "smsIntercept: Bundle -> Object[]");
        Object[] pdus = (Object[]) bundle.get("pdus");
        if (pdus.length <= 0) {
            return interceptedSms;
        }
        //Object[] -> SmsMessage[]
        Log.d(TAG, "smsIntercept: Object[] -> SmsMessage[]");
        SmsMessage[] messages = new SmsMessage[pdus.length];
        for (int i = 0; i < pdus.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        //SmsMessage[] -> InterceptedSms[]
        Log.d(TAG, "smsIntercept: SmsMessage[] -> InterceptedSms[]");
        interceptedSms = new InterceptedSms[messages.length];
        for (int i = 0; i < messages.length; i++) {
            interceptedSms[i] = new InterceptedSms();
            interceptedSms[i].setNumber(messages[i].getOriginatingAddress());
            interceptedSms[i].setContent(messages[i].getMessageBody());
            interceptedSms[i].setDateTime(new Date(messages[i].getTimestampMillis()));
            interceptedSms[i].setRemark("");
            Log.d(TAG, "smsIntercept: " + interceptedSms[i].toString());

        }
        return interceptedSms;
    }

    @SuppressLint("CheckResult")
    public static void smsIntercept(Context context, Intent intent, BroadcastReceiver receiver) {
        if (intent == null) {
            return;
        }
        if (!SettingFragment.isIntercept()) {
            return;
        }

        InterceptedSms[] interceptedSms = getInterceptedSms(intent);
        for (final InterceptedSms temp : interceptedSms) {
            if (whitePattern(temp.getNumber())) {
                return;
            }
            if (blackPattern(temp.getNumber())) {
                receiver.abortBroadcast();
                Completable.create(new CompletableOnSubscribe() {
                    @Override
                    public void subscribe(CompletableEmitter emitter) throws Exception {
                        HIDBUtil.getInterceptedSmsDao().addInterceptedSms(temp);
                        if (sSmsListAdapter != null) {
                            sSmsListAdapter.getInterceptedSms().add(0,temp);
                            sSmsListAdapter.selectInit(sSmsListAdapter.getInterceptedSms().size(), false);
                        }
                        emitter.onComplete();
                    }
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action() {
                            @Override
                            public void run() throws Exception {
                                if (sSmsListAdapter == null) {
                                    return;
                                }
                                if (sLinearLayoutManager == null) {
                                    return;
                                }
                                sSmsListAdapter.notifyDataSetChanged();
                                sLinearLayoutManager.scrollToPosition(0);
                            }
                        });
//                int res = context.getContentResolver().delete(Uri.parse("content://sms"), "address like '" + mobile + "'", null);
                return;
            }
        }
    }

    public static boolean blackPattern(String number) {
        List<BlackList> blackLists = HIDBUtil.getBlackListDao().getBlackListForModel(HIDatabase.DARK_MODEL);
        String regex = null;
        boolean result = false;
        for (BlackList blackList : blackLists) {
            regex = "^" + blackList.getNumber() + "\\d*$";
            result = number.matches(regex);
            Log.d(TAG, "blackPattern: " + number + ".matches(" + regex + ")正则匹配结果：" + result);
            if (result) {
                return blackList.isSms();
            }
        }
        BlackList blackList = HIDBUtil.getBlackListDao().getBlackListForNumber(number);
        if (blackList != null) {
            result = blackList.isSms();
        }
        return result;
    }

    public static boolean whitePattern(String number) {
        //得到模糊号码列表
        List<WhiteList> whiteLists = HIDBUtil.getWhiteListDao().getWhiteListForModel(HIDatabase.DARK_MODEL);
        String regex = null;
        boolean result = false;
        for (WhiteList whiteList : whiteLists) {
            regex = "^" + whiteList.getNumber() + "\\d*$";
            result = number.matches(regex);
            Log.d(TAG, "whitePattern: " + number + ".matches(" + regex + ")正则匹配结果：" + result);
            if (result) {
                return whiteList.isSms();
            }
        }
        //是否是精确号码
        WhiteList whiteList = HIDBUtil.getWhiteListDao().getWhiteListForNumber(number);
        if (whiteList != null) {
            result = whiteList.isSms();
        }
        return result;
    }

    public static SmsListAdapter getSmsListAdapter() {
        return sSmsListAdapter;
    }

    public static void setSmsListAdapter(SmsListAdapter smsListAdapter) {
        sSmsListAdapter = smsListAdapter;
    }

    public static LinearLayoutManager getLinearLayoutManager() {
        return sLinearLayoutManager;
    }

    public static void setLinearLayoutManager(LinearLayoutManager linearLayoutManager) {
        sLinearLayoutManager = linearLayoutManager;
    }
}
